<template>
<!-- 区域报销统计 -->
  <div class="reimbursement-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-card shadow="hover">
        <div class="search-form">
          <el-form :inline="true" :model="searchForm" class="demo-form-inline">
            <!-- <el-form-item label="农民姓名">
              <el-input v-model="searchForm.farmerName" placeholder="请输入农民姓名" clearable />
            </el-form-item>
            <el-form-item label="疾病名称">
              <el-select v-model="searchForm.diseaseName" placeholder="请选择疾病名称" clearable>
                <el-option
                  v-for="disease in diseaseOptions"
                  :key="disease"
                  :label="disease"
                  :value="disease"
                />
              </el-select>
            </el-form-item> -->
            <!-- <el-form-item label="审核状态">
              <el-select v-model="searchForm.auditStatus" placeholder="请选择审核状态" clearable>
                <el-option label="全部" value="" />
                <el-option label="待审核" value="待审核" />
                <el-option label="审核通过" value="审核通过" />
                <el-option label="已拒绝" value="已拒绝" />
              </el-select>
            </el-form-item> -->
            <el-form-item>
              <!-- <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="resetSearchForm">重置</el-button> -->
              <el-button type="success" @click="exportToExcel" :loading="exportLoading">
                <i class="el-icon-download" /> 导出Excel
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>

    <!-- 镇级统计图表 -->
    <div class="statistics-chart" v-if="hasTownStatistics">
      <el-card shadow="hover">
        <div ref="townChartContainer" style="height: 350px;"></div>
      </el-card>
    </div>
    
    <!-- 村级统计图表 -->
    <div class="statistics-chart" v-if="hasVillageStatistics">
      <el-card shadow="hover">
        <h3>村级报销统计</h3>
        <div ref="villageChartContainer" style="height: 350px;"></div>
      </el-card>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        :data="filteredPage?.records || []"
        border
        style="width: 100%; margin-top: 20px;display:flex"
        v-loading="loading"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column prop="reimbursementId" label="报销ID" width="120" align="center" />
        <el-table-column prop="farmerName" label="农民姓名" width="180" show-overflow-tooltip />
        <el-table-column prop="diseaseName" label="疾病名称" width="180" show-overflow-tooltip />
        <el-table-column prop="reimbursementAmount" label="报销金额" width="180" align="right">
          <template #default="{ row }">
            {{ formatNumber(row.reimbursementAmount) }} 元
          </template>
        </el-table-column>
        <el-table-column prop="reimbursementTime" label="申请时间" width="220">
          <template #default="{ row }">
            {{ formatDate(row.reimbursementTime) }}
          </template>
        </el-table-column>
        <el-table-column label="审核状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.auditStatus)">
              {{ row.auditStatus }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 无数据提示 -->
      <div v-if="!loading && (filteredPage?.records.length === 0 || !filteredPage)" class="no-data">
        <el-empty description="暂无报销记录" image-size="120px" />
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="filteredPage?.total > 0">
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredPage.total"
      />
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import { ElMessage, ElTag, ElEmpty } from 'element-plus'
import * as echarts from 'echarts'
import * as XLSX from 'xlsx' 

export default {
  name: 'ChronicDiseaseReimbursementList',
  data() {
    return {
      searchForm: {
        farmerName: '',
        diseaseName: '',
        auditStatus: ''
      },
      filteredPage: null,
      townStatistics: [],    // 镇级统计数据
      villageStatistics: [], // 村级统计数据
      loading: false,
      exportLoading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      townChart: null,
      villageChart: null,
      chartResizeHandler: null,
      diseaseOptions: []
    }
  },
  computed: {
    hasTownStatistics() {
      return this.townStatistics && this.townStatistics.length > 0;
    },
    hasVillageStatistics() {
      return this.villageStatistics && this.villageStatistics.length > 0;
    }
  },
  mounted() {
    this.fetchReimbursementData();
    // 监听窗口大小变化，更新图表
    this.chartResizeHandler = () => {
      if (this.townChart) this.townChart.resize();
      if (this.villageChart) this.villageChart.resize();
    };
    window.addEventListener('resize', this.chartResizeHandler);
  },
  methods: {
    // 格式化金额（千位分隔符，保留两位小数）
    formatNumber(amount) {
      if (isNaN(Number(amount))) return '0.00';
      return Number(amount)
        .toFixed(2)
        .replace(/\d{1,3}(?=(\d{3})+\.)/g, s => `${s},`);
    },

    // 格式化时间戳为日期字符串
    formatDate(timestamp, format = 'YYYY-MM-DD HH:mm:ss') {
      if (!timestamp) return '--';
      const date = new Date(timestamp);
      const formatMap = {
        YYYY: date.getFullYear(),
        MM: String(date.getMonth() + 1).padStart(2, '0'),
        DD: String(date.getDate()).padStart(2, '0'),
        HH: String(date.getHours()).padStart(2, '0'),
        mm: String(date.getMinutes()).padStart(2, '0'),
        ss: String(date.getSeconds()).padStart(2, '0')
      };
      return format.replace(/(YYYY|MM|DD|HH|mm|ss)/g, match => formatMap[match]);
    },

    // 获取状态标签颜色
    getStatusColor(status) {
      const colorMapping = {
        '审核通过': 'success',
        '已汇款': 'success',
        '待审核': 'warning',
        '已拒绝': 'danger',
        '汇款失败': 'danger',
        '待汇款': 'info',
        '默认': 'info'
      };
      return colorMapping[status] || colorMapping['默认'];
    },

    // 渲染镇级统计图表
    renderTownStatisticsChart() {
      if (!this.$refs.townChartContainer || !this.hasTownStatistics) return;

      if (this.townChart) {
        this.townChart.dispose();
        this.townChart = null;
      }

      const chartData = this.townStatistics.map(region => ({
        name: region.regionName,
        value: region.totalAmount,
        count: region.count
      }));

      this.$nextTick(() => {
        this.townChart = echarts.init(this.$refs.townChartContainer);
        this.townChart.setOption({
          // 图标标题
          title: { text: '镇级报销统计', subtext: '数据基于报销金额', left: 'center' },
          //鼠标悬停时显示的信息
          tooltip: {
            trigger: 'item',
            formatter: (params) => {
              const data = params.data;
              return `${data.name}<br/>次数：${data.count}次<br/>金额：${this.formatNumber(data.value)}元`;
            }
          },
          //图例配置
          legend: { orient: 'vertical', left: 'left', top: 'middle' },
          series: [{
            name: '镇级分布',
            type: 'pie',  //图类型
            radius: ['40%', '70%'], //环形饼图，内径40%，外径70%
            label: {
              formatter: (params) => `${params.data.name}: ${this.formatNumber(params.data.value)}元`
            },
            data: chartData   //图标数据
          }]
        });
      });
    },
    
    // 渲染村级统计图表
    renderVillageStatisticsChart() {
      if (!this.$refs.villageChartContainer || !this.hasVillageStatistics) return;

      if (this.villageChart) {
        this.villageChart.dispose();
        this.villageChart = null;
      }

      const chartData = this.villageStatistics.map(region => ({
        name: region.regionName,
        value: region.totalAmount,
        count: region.count
      }));

      this.$nextTick(() => {
        this.villageChart = echarts.init(this.$refs.villageChartContainer);
        this.villageChart.setOption({
          title: { text: '村级报销统计', subtext: '数据基于报销金额', left: 'center' },
          tooltip: {
            trigger: 'item',
            formatter: (params) => {
              const data = params.data;
              return `${data.name}<br/>次数：${data.count}次<br/>金额：${this.formatNumber(data.value)}元`;
            }
          },
          legend: { orient: 'vertical', left: 'left', top: 'middle' },
          series: [{
            name: '村级分布',
            type: 'pie',
            radius: ['40%', '70%'],
            label: {
              formatter: (params) => `${params.data.name}: ${this.formatNumber(params.data.value)}元`
            },
            data: chartData
          }]
        });
      });
    },

    // 加载报销数据
    async fetchReimbursementData() {
      this.loading = true;
      try {
        const response = await request.get('/chronicDiseaseReimbursement/list2', {
          params: {
            current: this.pagination.currentPage,
            size: this.pagination.pageSize,
            ...this.searchForm
          }
        });

        if (response.code !== 200) {
          throw new Error(response.message || '数据加载失败');
        }

        const { page, townStats, villageStats } = response.data;
        
        this.filteredPage = {
          records: page.records,
          total: page.total
        };
        this.pagination.total = this.filteredPage.total;
        
        // 分别存储镇级和村级统计数据
        this.townStatistics = townStats || [];
        this.villageStatistics = villageStats || [];
        
        // 分别渲染镇级和村级图表
        this.$nextTick(() => {
          this.renderTownStatisticsChart();
          this.renderVillageStatisticsChart();
        });

      } catch (error) {
        console.error('数据加载错误:', error);
        ElMessage.error(error.message || '加载报销记录失败');
        this.filteredPage = { records: [], total: 0 };
        this.townStatistics = [];
        this.villageStatistics = [];
        this.renderTownStatisticsChart();
        this.renderVillageStatisticsChart();
      } finally {
        this.loading = false;
      }
    },

    // 搜索处理
    handleSearch() {
      this.pagination.currentPage = 1;
      this.fetchReimbursementData();
    },

    // 重置搜索条件
    resetSearchForm() {
      this.searchForm = {
        farmerName: '',
        diseaseName: '',
        auditStatus: ''
      };
      this.handleSearch();
    },

    // 分页大小变更
    handlePageSizeChange(size) {
      this.pagination.pageSize = size;
      this.pagination.currentPage = 1;
      this.fetchReimbursementData();
    },

    // 当前页变更
    handleCurrentPageChange(page) {
      this.pagination.currentPage = page;
      this.fetchReimbursementData();
    },

    // 导出Excel文件
    async exportToExcel() {
      this.exportLoading = true;
      try {
        // 准备镇级统计数据
        const townData = this.townStatistics.map(town => ({
          '镇区域代码': town.regionCode,
          '镇名称': town.regionName,
          '报销次数': town.count,
          '报销总金额(元)': town.totalAmount
        }));

        // 准备记录数据
        const recordsData = (this.filteredPage?.records || []).map(record => ({
          '报销ID': record.reimbursementId,
          '农民姓名': record.farmerName,
          '疾病名称': record.diseaseName,
          '报销金额(元)': record.reimbursementAmount,
          '申请时间': this.formatDate(record.reimbursementTime),
          '审核状态': record.auditStatus,
          '汇款状态': record.remittanceStatus
        }));

        // 创建工作簿
        const wb = XLSX.utils.book_new();

        // 创建镇级统计表
        const townWS = XLSX.utils.json_to_sheet(townData);
        XLSX.utils.sheet_add_aoa(townWS, [['镇级报销统计']], { origin: 'A1' });
        XLSX.utils.sheet_add_aoa(townWS, [[]], { origin: 'A2' }); // 空行
        // 移动数据以留出标题空间
        XLSX.utils.sheet_add_json(townWS, townData, { origin: 'A3', skipHeader: true });
        XLSX.utils.book_append_sheet(wb, townWS, '镇级统计');

        // 创建记录表格
        const recordsWS = XLSX.utils.json_to_sheet(recordsData);
        XLSX.utils.sheet_add_aoa(recordsWS, [['慢病报销记录']], { origin: 'A1' });
        XLSX.utils.sheet_add_aoa(recordsWS, [[]], { origin: 'A2' }); // 空行
        // 移动数据以留出标题空间
        XLSX.utils.sheet_add_json(recordsWS, recordsData, { origin: 'A3', skipHeader: true });
        XLSX.utils.book_append_sheet(wb, recordsWS, '报销记录');

        // 自动调整列宽
        this.autoSizeColumns(townWS, townData);
        this.autoSizeColumns(recordsWS, recordsData);

        // 生成文件名
        const fileName = `慢病报销记录_${new Date().toLocaleDateString()}.xlsx`;

        // 导出文件
        XLSX.writeFile(wb, fileName);
        ElMessage.success('导出成功');
      } catch (error) {
        console.error('导出失败:', error);
        ElMessage.error('导出失败，请重试');
      } finally {
        this.exportLoading = false;
      }
    },

    // 自动调整列宽
    autoSizeColumns(worksheet, data) {
      const columnWidths = [];
      
      // 计算表头宽度
      const headers = Object.keys(data[0] || {});
      headers.forEach((header, index) => {
        columnWidths[index] = { wch: header.length + 2 }; // 增加2个字符的边距
      });
      
      // 计算每列数据的最大宽度
      data.forEach(row => {
        headers.forEach((header, index) => {
          const cellValue = row[header] === undefined ? '' : row[header].toString();
          const cellWidth = cellValue.length + 2; // 增加2个字符的边距
          if (cellWidth > (columnWidths[index]?.wch || 0)) {
            columnWidths[index] = { wch: cellWidth };
          }
        });
      });
      
      // 设置列宽
      worksheet['!cols'] = columnWidths;
    }
  },
  beforeUnmount() {
    // 销毁两个图表实例
    if (this.townChart) this.townChart.dispose();
    if (this.villageChart) this.villageChart.dispose();
    if (this.chartResizeHandler) {
      window.removeEventListener('resize', this.chartResizeHandler);
    }
  }
}
</script>

<style scoped>
.reimbursement-container {
  padding: 24px;
  background-color: #f8f9fa;
}

.search-container {
  margin-bottom: 24px;
}

.search-form {
  display: flex;
  align-items: center;
}

.statistics-chart {
  margin-bottom: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.table-container {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.no-data {
  text-align: center;
  padding: 80px 20px;
  color: #909399;
}

.pagination-container {
  margin-top: 40px;
  text-align: right;
  padding-right: 24px;
}

.el-table__header-wrapper {
  overflow-x: hidden;
}

.el-table-column--right .el-table__cell {
  padding-right: 32px;
}

/* 状态标签动画 */
.el-tag {
  transition: all 0.3s ease;
}

.el-tag:hover {
  transform: scale(1.05);
}

/* 导出按钮样式 */
.el-button.success {
  margin-left: 10px;
}
</style>
    